package com.wuwei.elearning.question.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wuwei.elearning.exception.ElearningMysqlException;
import com.wuwei.elearning.question.domain.Grade;
import com.wuwei.elearning.question.domain.QuestionItem;
import com.wuwei.elearning.question.domain.TestResult;
import com.wuwei.elearning.question.mapper.GradeMapper;
import com.wuwei.elearning.question.mapper.QuestionItemMapper;
import com.wuwei.elearning.question.mapper.TestResultMapper;
import com.wuwei.elearning.question.service.GradeService;
import com.wuwei.elearning.setting.domain.User;
import com.wuwei.elearning.setting.mapper.UserMapper;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import com.wuwei.elearning.vo.GradeDto;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 * <p>
 * 班级表,一个班级有很多学员和一个班主任 前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-08-12
 */
@RestController
@RequestMapping("/elearning/grade")
@CrossOrigin
public class GradeController {

    @Resource
    private GradeService gradeService;

    @Resource
    private GradeMapper grademapper;

    @PostMapping("add")
    public Result<String> add(@RequestBody GradeDto gradeDto, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        Integer grade = gradeDto.getGrade();
        Integer year = gradeDto.getYear();
        Integer type = gradeDto.getType();
        String gradeName = year+"年第"+grade+"期";
        if (type ==0) {
            if (gradeDto.getLicense().size()==1) {
                Integer licenseType = gradeDto.getLicense().get(0);
                if (licenseType == 0) {
                    gradeName+="TA班";
                } else {
                    gradeName+="PA班";
                }
            } else {
                gradeName += "PA+TA班";
            }
        } else {
            gradeName+="DA42机型班";
        }
        gradeService.add(gradeName,gradeDto.getStudents(),account,gradeDto.getType(),gradeDto.getTeacher());
        return Result.ok("添加成功！");
    }

    @PostMapping("update")
    public Result<String> update(@RequestBody GradeDto gradeDto, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);
        Integer grade = gradeDto.getGrade();
        Integer year = gradeDto.getYear();
        Integer type = gradeDto.getType();
        String gradeName = year+"年第"+grade+"期";
        if (type ==0) {
            if (gradeDto.getLicense().size()==1) {
                Integer licenseType = gradeDto.getLicense().get(0);
                if (licenseType == 0) {
                    gradeName+="TA班";
                } else {
                    gradeName+="PA班";
                }
            } else {
                gradeName += "PA+TA班";
            }
        }
        gradeService.myUpdate(gradeDto.getId(),gradeName,gradeDto.getStudents(),account,gradeDto.getType(),gradeDto.getTeacher());
        return Result.ok("更新成功！");
    }

    @GetMapping("all")
    public Result<List<Grade>> all (){
        List<Grade> list = gradeService.list();
        return Result.ok(list);
    }


    /**
     * 获取所有基础执照班级
     * @return
     */
    @GetMapping("allR3")
    public Result<List<Grade>> allR3 (){
        LambdaQueryWrapper<Grade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Grade::getType,0);
        List<Grade> list = grademapper.selectList(queryWrapper);
        return Result.ok(list);
    }

    @GetMapping("list/{name}/{currentPage}/{pageSize}")
    public Result<List<Grade>> list (@PathVariable("name") String name,@PathVariable("currentPage") Integer currentPage,
                                     @PathVariable("pageSize") Integer pageSize){
        LambdaQueryWrapper<Grade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!name.equals("_"),Grade::getName,name);
        IPage<Grade> page = new Page<>();
        page.setCurrent(currentPage);
        page.setSize(pageSize);
        IPage<Grade> gradeIPage = gradeService.page(page, queryWrapper);
        List<Grade> records = gradeIPage.getRecords();
        return Result.ok(records);
    }

    @GetMapping("total/{name}")
    public Result<Long> total (@PathVariable("name") String name){
        LambdaQueryWrapper<Grade> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!name.equals("_"),Grade::getName,name);
        long count = gradeService.count(queryWrapper);
        return Result.ok(count);
    }

    @DeleteMapping("delete/{id}")
    public Result<String> delete (@PathVariable("id") Long id){
        gradeService.myRemove(id);
        return Result.ok("删除成功！");
    }

    @Resource
    private TokenUtil tokenUtil;

    @Resource
    private UserMapper userMapper;

    @Resource
    private TestResultMapper testResultMapper;

    @Resource
    private QuestionItemMapper questionItemMapper;


    /**
     * 查询某名学生在该班级平均分的排名
     * 平均分的计算规则：
     * 每名学员的平均分等于他的考试试卷的总分除以出给他这个班级和他所上科目的所有试卷
     * 1.查询该学生所在班级的所有其他学员
     * 2.查询该名学员和所有其他学员的平均分
     */
    @GetMapping("getUserRank")
    public Result<Integer> getUserRank(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        User user = tokenUtil.getUserFromToken(token);
        int rank = gradeService.getUserRank(user);
        return Result.ok(rank);
    }



    /**
     * 统计学员各科的平均分
     * @param subjectId
     * @param gradeId
     * @return
     */
    @GetMapping("getStatictics/{subjectId}/{gradeId}")
    public Result<Map<String,Object>> getStatictics(@PathVariable("subjectId")Long subjectId, @PathVariable("gradeId")Long gradeId){
        Map<String, Object> map = gradeService.getStatictics(subjectId, gradeId);
        return Result.ok(map);
    }

    /**
     * 查找某学员的某科成绩分数变化情况
     * @param subjectId
     * @param gradeId
     * @param account
     * @return
     */
    @GetMapping("showDetail/{subjectId}/{gradeId}/{account}")
    public Result<Map<String,Object>> showDetail(@PathVariable("subjectId")Long subjectId, @PathVariable("gradeId")Long gradeId,
                                                 @PathVariable("account") Long account
    ){
        Map<String, Object> map = gradeService.showDetail(subjectId, gradeId,account);
        return Result.ok(map);
    }

}

